// Copyright 2021 Guoyoko. All Rights Reserved.

#include "Core/SWDetailBuilder.h"
#include "Widgets/Views/STreeView.h"
#include "Widgets/Views/STableRow.h"
#include "Widgets/Views/STableViewBase.h"
#include "Slate/SSWDetailCategoryTableRow.h"
#include "Slate/SSWDetailSingleItemRow.h"


FSWDetailNode& FSWDetailBuilder::AddCategory(FName InCategoryName, FName InCategoryDisplayName, TSharedPtr<SWidget> InNodeWidget)
{

	TSharedPtr<FSWDetailNode> NewNode = MakeShareable(new FSWDetailNode(InCategoryName, InCategoryDisplayName, InNodeWidget));

	NewNode->bIsCategory = true;

	TreeSource.Add(NewNode);

	return *NewNode.Get();
}

TSharedPtr<SWidget> FSWDetailBuilder::BuildDetail()
{
	SAssignNew(TreeView, STreeView< TSharedPtr<FSWDetailNode>>)
		.TreeItemsSource(&TreeSource)
		.ItemHeight(24)
		.OnGenerateRow(this, &FSWDetailBuilder::OnGenerateRowForTree)
		.OnGetChildren(this, &FSWDetailBuilder::OnGetChildrenForTree)
		.SelectionMode(ESelectionMode::None);

	for (auto& Item : TreeSource)
	{
		TreeView->SetItemExpansion(Item, Item->bDefaultExpanded);
	}

	return
		SNew(SBox)
		.Padding(FMargin(2, 0, 0, 0))
		[
			TreeView.ToSharedRef()
		];
}

TSharedRef<ITableRow> FSWDetailBuilder::OnGenerateRowForTree(TSharedPtr<FSWDetailNode> InItem, const TSharedRef<STableViewBase>& OwnerTable)
{
	if (InItem->bIsCategory)
	{
		return 	
			SNew(SSWDetailCategoryTableRow, InItem.ToSharedRef(), OwnerTable);
	}
	else
	{
		return 	
			SNew(SSWDetailSingleItemRow, InItem.ToSharedRef(), OwnerTable);
	}

}

void FSWDetailBuilder::OnGetChildrenForTree(TSharedPtr<FSWDetailNode> InParent, TArray<TSharedPtr<FSWDetailNode>>& OutChildren)
{
	OutChildren = InParent->GetChildNodes();
}

